import { profile } from '@/utils/decorators';
import { Logger } from '@/utils/logger';
import { Colony } from '../Colony';
import { RoomPlanner } from './planner';

const PLAN_BUCKET_REQUIREMENT = 150;

/**
 * 管理自动规划建筑的操作
 */
export class RoomPlannerManager {

    public readonly colony: Colony;

    constructor(colony: Colony) {
        this.colony = colony;
    }

    @profile
    replan() {
        // 规划建筑
        if (Game.cpu.bucket <= PLAN_BUCKET_REQUIREMENT) {
            Logger.warn('无法规划建筑，因为 CPU bucket 不足', 'autoplan');
            return false;
        }
        Logger.info(`重新规划殖民地 "${this.colony.name}" 的建筑`, 'autoplan');
        const planResult = (new RoomPlanner).plan(this.colony.capital);
        Logger.info(`规划完毕，消耗了 ${planResult.deltaTime} CPU`);

        const { sequence } = planResult;

        // 初始化数据结构
        this.colony.memory.structurePlan = {};
        for (let i = 2; i <= 8; ++i) {
            this.colony.memory.structurePlan[i] = {};
        }

        // 分配建造个数
        // 所有的到 source 的道路都在三级建造
        this.colony.memory.structurePlan[3][STRUCTURE_ROAD] = planResult.roads;
        // 合并结果
        const distribute = (struct: BuildableStructureConstant, fromLevel = 2, specLimit?: number) => {
            const buildMax = CONTROLLER_STRUCTURES[struct];
            if (!sequence[struct]) {
                return;
            }
            for (let level = fromLevel; level <= 8; ++level) {
                if (!sequence[struct].length) {
                    continue;
                }
                const limit = specLimit ? specLimit : buildMax[level] - buildMax[level - 1];
                if (!this.colony.memory.structurePlan[level][struct]) {
                    this.colony.memory.structurePlan[level][struct] = [];
                }
                for (let i = 0; i < limit; ++i) {
                    const p = sequence[struct].shift();
                    if (p) {
                        this.colony.memory.structurePlan[level][struct].push(p);
                    }
                }
            }
        };
        Object.keys(CONSTRUCTION_COST).forEach(_structureType => {
            const structureType = <BuildableStructureConstant>_structureType;
            if (structureType === STRUCTURE_ROAD) {
                distribute(STRUCTURE_ROAD, 3, 15);
            }
            else {
                distribute(structureType);
            }
        });
        Logger.info('建筑建造时间分配完毕', 'autoplan')
    }

}